
const axios = require('axios');



const DataService = require('./form/DataService.js')
module.exports = class EasyisApiClient{
	constructor(config){// url accessKey accessSecret
        this.config = config
        const instance = axios.create({
            baseURL: config.url || 'https://easyis.xiaoyung.com/prod-api',//'https://api.example.com',
            timeout: config.timeout || 5000,
            headers: Object.assign({
                'Content-Type': 'application/json;charset=UTF-8'
            },config.headers),
            validateStatus: function (status) {
                //默认 return status >= 200 && status < 300
                return (status >= 200 && status < 300) || status == 401 // 这里将成功状态码范围修改为 200 - 499,因为401默认为错误
            },
        });
        this.request = instance
        const self = this
        

        instance.interceptors.request.use(async function (config) {
            //表单返回数据 字段名转驼峰模式
            if(!self.config.camleNameModel || self.config.camleNameModel==true){
                if(!config.params){
                    config.params={}
                }
                config.params['camleNameModel'] = true
            }
            //console.log('config.url 是什么?全部url还是部分?',config.url)//  /openapi/form/dataService/insert
            if (!config.url.includes('/auth/openapi/getToken')) {// undefined/auth/openapi/getToken
                /* if(self.config?.headers){
                    for(let key in self.config.headers){
                        config.headers[key] = self.config.headers[key]
                    }
                } */
                
                config.headers['Authorization'] = await self.getToken(self)
            }

            return config;
        }, function (error) {
            return Promise.reject(error);
        });
        
        instance.interceptors.response.use(function (response) {
            /* if(response.status!=200){//要不要这个呢?好像会自动报错吧
                throw new Error('http status code异常',response.status)
            } */
            //console.log('result: ',response.data)
            const result = response.data
            if(result.code!=200){//response.data={code:401,msg:'已过期'}
                //throw new Error('业务异常 code:'+response.data.code+' '+response.data.msg)
                throw new Error(JSON.stringify(result))
            }

            return result
        }, function (error) {
            return Promise.reject(error);
        });
        
        //this.dataService = new DataService(instance)

      
    }

    async getToken(self){
        if(self.config.accessToken){
            console.log('===直接使用 accessToken====')     
            return self.config.accessToken
        }else{
            let token = self.token
            if(token){
                if(new Date() > token.expiresAt){//如果token过期了
                    token = null
                    self.token = null
                }
            }
    
            if(!token){
                console.log('===通过 sk sk 获取 accessToken====')

                const url = self.config.url
                const accessKey = self.config.accessKey
                const accessSecret = self.config.accessSecret
                const result = await self.request({
                    method:'post',
                    url: '/auth/openapi/getToken',
                    data: {accessKey,accessSecret}
                })
                //const result = response.data
                const {data,code,msg} = result
                console.log('getToken: ',data)
                if(code==200){
                    const expiresAt = new Date()
                    expiresAt.setTime(expiresAt.getTime() + (data.expiresIn - 60) * 1000)// 提前60s 钟过期
                    data.expiresAt = expiresAt
                    
                    token = data
                    self.token = data
    
                }else{                
                    throw new Error(JSON.stringify(result))
                    //throw new Error(msg)
                }
            }
            return token.accessToken
        }
        
    }
   
}


